/**
 * index for sysu engine!
 * @author HuangDell Chenwy HeLongX JiangZH
 */
#ifndef MYSQL_SYSU_INDEX_H
#define MYSQL_SYSU_INDEX_H

#include"my_global.h"
#include"my_sys.h"
#define byte unsigned char

const long METADATA_SIZE=sizeof(int)+sizeof(bool);
/* memory key for index */
static PSI_memory_key sysu_key_memory_index;
/*
 * This is the node that stores the key and the file position for the data row.
 */
struct SDE_INDEX{
    unsigned char *key;
    long long pos;
    int length;
};
/*
 * defines (doubly) linked list for internal list
 */
struct SDE_NDX_NODE{
    SDE_INDEX key_ndx;
    SDE_NDX_NODE *next;
    SDE_NDX_NODE *prev;
};

class Sysu_index{
public:
    Sysu_index(int keylen);
    Sysu_index();
    ~Sysu_index(void);
    int open_index(char * path);
    long long get_index_pos(byte *buf, int key_len);
    long long get_first_pos();
    byte *get_first_key();
    byte *get_last_key();
    byte *get_next_key();
    byte *get_prev_key();
    int close_index();
    int load_index();
    int destroy_index();
    SDE_INDEX *seek_index(unsigned char *key,int key_len);
    SDE_NDX_NODE *seek_index_pos(unsigned char *key,int key_len);
    int save_index();
    int trunc_index();
    int create_index(char *path, int keylen);
    int insert_key (SDE_INDEX *ndx,bool allow_dupes);
    int delete_key(byte *buf,long long pos,int key_len);
    int update_key(byte *buf,long long pos,int key_len);
private:
    File index_file;
    int max_key_len;
    SDE_NDX_NODE *root;
    SDE_NDX_NODE *range_ptr;
    int block_size;
    bool crashed;
    int read_header();
    int write_header();
    long long write_row(SDE_INDEX *ndx);
    SDE_INDEX *read_row(long long Position);
    long long curfpos();
};


#endif //MYSQL_SYSU_INDEX_H
